package com.bidevalution.business.common;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;

import java.io.File;
import java.nio.charset.Charset;

public class AnalysisZip4jUtil {
    public static void unZip(File file, String dest, String pass) throws ZipException {
        ZipFile zFile = new ZipFile(file);
        zFile.setCharset(Charset.forName("GBK"));
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        File destDir = new File(dest);
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(pass.toCharArray());
        }
        zFile.extractAll(dest);
    }

    public static void zip(String inputPath, String outputPath) throws ZipException {
        ZipFile zipFile = new ZipFile(outputPath);
        ZipParameters parameters = new ZipParameters();
//        // 压缩方式
//        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//        // 压缩级别
//        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        // 要打包的文件夹
        File currentFile = new File(inputPath);
        File[] fs = currentFile.listFiles();
        // 遍历test文件夹下所有的文件、文件夹
        if(fs!=null) {
            for (File f : fs) {
                if(f.isDirectory()) {
                    zipFile.addFolder(f, parameters);
                } else {
                    zipFile.addFile(f, parameters);
                }
            }
        }
    }
}
